<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="zheng_tops">
        <div class="zheng_center">
          <n-button type="primary" @click="newContent"> 新建 </n-button>
          <n-button type="error" @click="deleContent" style="margin-left: 20px">
            批量删除
          </n-button>
          <div class="searchs">
            <n-input
              placeholder="搜索用户ID"
              style="width: 270px; margin-left: 20px"
              v-model:value="inputValue"
            >
              <template #prefix>
                <n-icon :component="FlashOutline" />
              </template>
            </n-input>
            <n-button type="primary" @click="searchig" style="margin-left: 10px"> 搜索 </n-button>
          </div>
        </div>
        <div class="right_but">
          <n-button type="primary" @click="refresh"> 刷新 </n-button>
          <n-button type="success" @click="portexcel"> 导出excel </n-button>
        </div>
      </div>
      <div style="height: 20px"></div>
      <n-data-table
        striped
        v-if="tables.isReloadData"
        :columns="columns"
        :data="allData"
        :pagination="pagination"
        :row-key="rowKey"
        :align="right"
        :scroll-x="1500"
        @update:checked-row-keys="handleCheck"
      />
    </n-card>
    <!-- 编辑 -->
    <n-modal
      v-model:show="showModals"
      :mask-closable="false"
      :on-after-leave="modelClose"
      preset="dialog"
      title="编辑"
    >
      <div>
        <n-form
          ref="formRef"
          :model="tableDate"
          :rules="rules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="证书名称" path="name">
            <n-input v-model:value="tableDate.name" placeholder="请输入证书名称" />
          </n-form-item>
          <n-form-item label="证书编号" path="number">
            <n-input v-model:value="tableDate.number" placeholder="请输入证书编号" />
          </n-form-item>
          <n-form-item label="证书等级" path="level">
            <n-select
              v-model:value="tableDate.level"
              placeholder="请选择等级"
              :options="generalOptions"
            />
          </n-form-item>
          <n-form-item label="获得时间" path="time">
            <n-date-picker
              v-model:formatted-value="formattedValue"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
            />
          </n-form-item>
          <n-form-item label="复审时间" path="times">
            <n-date-picker
              v-model:formatted-value="formattedValues"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              clearable
            />
          </n-form-item>
          <div style="display: flex">
            <p style="width: 100px">照片</p>
            <n-upload
              action="/api/api/common/upload"
              :default-file-list="defaultFileList"
              list-type="image-card"
              @preview="handlePreview"
              @change="uploads"
            />
          </div>
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClick"> 保存 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
    <!-- 新建 -->
    <n-modal v-model:show="showNew" :mask-closable="false" preset="dialog" title="新建">
      <div>
        <n-form
          ref="formRefs"
          :model="newModel"
          :rules="newRules"
          label-placement="left"
          label-width="auto"
          require-mark-placement="right-hanging"
          :size="size"
          :style="{
            maxWidth: '640px',
          }"
        >
          <n-form-item label="用户ID" path="id">
            <n-input v-model:value="newModel.id" placeholder="请输入证书名称" />
          </n-form-item>
          <n-form-item label="证书名称" path="name">
            <n-input v-model:value="newModel.name" placeholder="请输入证书名称" />
          </n-form-item>
          <n-form-item label="证书编号" path="number">
            <n-input v-model:value="newModel.number" placeholder="请输入证书编号" />
          </n-form-item>
          <n-form-item label="证书等级" path="level">
            <n-select
              v-model:value="newModel.selectValue"
              placeholder="请选择等级"
              :options="generalOptions"
            />
          </n-form-item>
          <n-form-item label="获得时间" path="time">
            <n-date-picker v-model:value="newModel.time" type="date" />
          </n-form-item>
          <n-form-item label="复审时间" path="times">
            <n-date-picker v-model:value="newModel.times" type="date" />
          </n-form-item>
          <div style="display: flex">
            <p style="width: 100px">照片</p>
            <n-upload
              action="/api/api/common/upload"
              :default-file-list="previewFileLists"
              list-type="image-card"
              @preview="handlePreview"
              @before-upload="upload"
              max="1"
            />
          </div>
          <div style="display: flex; justify-content: flex-end">
            <n-button round type="primary" @click="handleValidateButtonClicks"> 确认 </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>
<script>
  import { h, ref, defineComponent, getCurrentInstance, reactive, nextTick } from 'vue';
  import { useMessage, NButton, NImage, useDialog } from 'naive-ui';
  import { FlashOutline } from '@vicons/ionicons5';
  import qs from 'qs';
  import table2excel from 'js-table2excel';

  const createColumns = ({ play, dele }) => {
    return [
      {
        type: 'selection',
      },
      {
        title: 'ID',
        key: 'id',
        width: 50,
      },
      {
        title: '证书名称',
        key: 'name',
        width: 120,
      },
      {
        title: '等级',
        key: 'level',
        width: 80,
      },
      {
        title: '用户',
        key: 'u_name',
        width: 80,
      },
      {
        title: '用户身份证',
        key: 'u_id_number',
        width: 180,
      },
      {
        title: '用户手机号',
        key: 'u_tel',
        width: 120,
      },
      {
        title: '证书编号',
        key: 'number',
      },
      {
        title: '照片',
        key: 'photos',
        width: 55,
        render(row) {
          return h(NImage, {
            size: 24,
            src: row.photos,
          });
        },
      },
      {
        title: '获得时间',
        key: 'gain_time',
      },
      {
        title: '复审时间',
        key: 'review_time',
      },
      {
        title: '创建时间',
        key: 'create_time',
      },
      {
        title: '更新时间',
        key: 'update_time',
      },
      {
        title: '操作',
        fixed: 'right',
        width: 80,
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'info',
              onClick: () => play(row),
            },
            { default: () => '编辑' }
          );
        },
      },
      {
        key: 'actions',
        width: 80,
        fixed: 'right',
        render(row) {
          return h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => dele(row),
            },
            { default: () => '删除' }
          );
        },
      },
    ];
  };

  export default defineComponent({
    setup() {
      const allData = ref();
      const message = useMessage();
      const showModals = ref(false);
      const showNew = ref(false);
      const showModalRef = ref(false);
      const checkedRowKeysRef = ref([]);
      const formRef = ref(null);
      const formRefs = ref(null);
      const tableDate = ref({});
      const dialog = useDialog();
      const inputValue = ref('');
      const checkKeys = reactive({
        deleall: [],
        checkKey: [],
        checkKeyAll: [],
      });
      const generalOptions = ref([
        {
          label: 1,
          value: 1,
        },
        {
          label: 2,
          value: 2,
        },
        {
          label: 3,
          value: 3,
        },
      ]);
      const newModel = reactive({
        id: '',
        name: '',
        level: '',
        selectValue: '',
        number: '',
        time: null,
        times: null,
      });
      let { proxy } = getCurrentInstance();
      const lists = () => {
        proxy
          .$axios({
            url: '/api/certificate/index/index', //列表数据
            method: 'post',
            data: {
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res.data.data.list);
            allData.value = res.data.data.list;
          });
      };
      lists();
      //点击新建
      const newContent = () => {
        showNew.value = true;
      };
      //批量删除
      const deleContent = () => {
        for (let i = 0; i < checkKeys.checkKey.length; i++) {
          checkKeys.deleall.push(checkKeys.checkKey[i].id);
        }
        console.log(checkKeys.deleall);
        if (checkKeys.checkKeyAll.length != 0) {
          dialog.warning({
            title: '删除',
            content: '确定要删除吗',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {
              proxy
                .$axios({
                  url: '/api/certificate/index/del',
                  method: 'post',
                  data: {
                    id: checkKeys.deleall,
                    admin_id: 111,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res.data);
                  if (res.code == 1) {
                    message.success('删除成功');
                    lists();
                  }
                });
            },
          });
        } else {
          message.error('请勾选内容');
        }
      };
      //搜索
      const searchig = () => {
        console.log(inputValue.value);
        proxy
          .$axios({
            url: '/api/certificate/index/user_certificate',
            method: 'post',
            data: {
              uid: inputValue.value,
              admin_id: 111,
              admin_name: '张',
            },
          })
          .then((res) => {
            console.log(res.data);
            allData.value = res.data;
          });
      };
      // 上传图片
      const upimage = ref();
      function upload(e) {
        console.log(e);
        let param = new FormData(); //创建form对象
        param.append('file', e.file.file, e.file.file.name); //通过append向form对象添加数据
        proxy
          .$axios({
            url: '/api/api/common/upload',
            method: 'post',
            data: param,
          })
          .then((res) => {
            console.log(res.data.url);
            upimage.value = res.data.url;
          });
      }
      //编辑上传图片
      const upimages = ref();
      const image = ref();
      const uploads = (e) => {
        let params = new FormData(); //创建form对象
        params.append('file', e.file.file, e.file.file.name); //通过append向form对象添加数据
        proxy
          .$axios({
            url: '/api/api/common/upload',
            method: 'post',
            data: params,
          })
          .then((res) => {
            console.log(res.data.url);
            upimages.value = res.data.url;
          });
      };
      const timestampToTime = (timestamp) => {
        let datesd = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = datesd.getFullYear() + '-';
        let M =
          (datesd.getMonth() + 1 < 10 ? '0' + (datesd.getMonth() + 1) : datesd.getMonth() + 1) +
          '-';
        let D = datesd.getDate() < 10 ? '0' + datesd.getDate() : datesd.getDate();
        return Y + M + D;
      };
      // console.log(timestampToTime());
      //对话框关闭
      const modelClose = () => {
        defaultFileList.value = [];
      };
      // 上传图片默认显示图片
      const defaultFileList = ref([]);
      const formattedValue = ref('');
      const formattedValues = ref('');
      const editorImage = ref();
      //刷新
      const tables = reactive({
        isReloadData: true,
      });
      const refresh = () => {
        tables.isReloadData = false;
        setTimeout(() => {
          nextTick(() => {
            tables.isReloadData = true;
          });
        }, 400);
      };
      // 导出
      const portexcel = () => {
        const excelName = '信息反馈';
        const column = [
          {
            title: 'ID',
            key: 'id',
            width: 50,
          },
          {
            title: '证书名称',
            key: 'name',
            width: 120,
          },
          {
            title: '等级',
            key: 'level',
            width: 80,
          },
          {
            title: '用户',
            key: 'u_name',
            width: 80,
          },
          {
            title: '用户身份证',
            key: 'u_id_number',
            width: 180,
          },
          {
            title: '用户手机号',
            key: 'u_tel',
            width: 120,
          },
          {
            title: '证书编号',
            key: 'number',
          },
          {
            title: '照片',
            key: 'photos',
            type: 'image',
            width: 80,
            height: 50,
          },
          {
            title: '获得时间',
            key: 'gain_time',
          },
          {
            title: '复审时间',
            key: 'review_time',
          },
          {
            title: '创建时间',
            key: 'create_time',
          },
          {
            title: '更新时间',
            key: 'update_time',
          },
        ];
        if (checkKeys.checkKey.length == 0) {
          message.error('您未选中导出项');
        } else {
          message.success('正在导出中......');
          table2excel(column, checkKeys.checkKey, excelName);
          message.success('导出成功');
          checkKeys.checkKey = [];
        }
      };
      const paginationReactive = reactive({
        page: 1,
        pageSize: 5,
        showSizePicker: true,
        pageSizes: [3, 5, 7],
        onChange: (page) => {
          paginationReactive.page = page;
        },
        onUpdatePageSize: (pageSize) => {
          paginationReactive.pageSize = pageSize;
          paginationReactive.page = 1;
        },
      });
      return {
        allData,
        FlashOutline,
        newContent,
        showNew,
        formRef,
        formRefs,
        tableDate,
        searchig,
        inputValue,
        upload,
        upimage,
        checkKeys,
        deleContent,
        uploads,
        upimages,
        image,
        timestampToTime,
        defaultFileList,
        modelClose,
        formattedValue,
        formattedValues,
        editorImage,
        refresh,
        tables,
        portexcel,
        columns: createColumns({
          play(row) {
            console.log(row);
            tableDate.value = row;
            formattedValue.value = tableDate.value.gain_time;
            formattedValues.value = tableDate.value.review_time;
            defaultFileList.value = row.photos.map((item) => {
              return {
                status: 'finished',
                url: item,
              };
            });
            showModals.value = true;
          },
          dele(row) {
            console.log(row.id);
            dialog.warning({
              title: '删除',
              content: '你确定要删除吗？',
              positiveText: '确定',
              negativeText: '不确定',
              onPositiveClick: () => {
                proxy
                  .$axios({
                    url: '/api/certificate/index/del',
                    method: 'post',
                    data: {
                      id: row.id,
                      admin_id: 111,
                      admin_name: '张',
                    },
                  })
                  .then((res) => {
                    console.log(res.data);
                    if (res.code == 1) {
                      message.success('删除成功');
                      lists();
                    }
                  });
              },
              onNegativeClick: () => {},
            });
          },
        }),
        checkedRowKeys: checkedRowKeysRef,
        pagination: paginationReactive,
        rowKey: (row) => row,
        handleCheck(rowKeys) {
          checkKeys.checkKey = rowKeys;
        },
        // 编辑弹窗
        showModals,
        showModal: showModalRef,
        // 弹窗表单
        model: ref({
          name: null,
          level: null,
          number: null,
          time: null,
          times: null,
        }),
        newModel,
        generalOptions,
        rules: {
          name: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          number: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          gain_time: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          review_time: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
        },
        newRules: {
          id: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          name: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          number: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入内容',
          },
          time: {
            type: 'number',
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入内容',
          },
          times: {
            type: 'number',
            required: true,
            trigger: ['blur', 'change'],
            message: '请输入内容',
          },
        },
        handleValidateButtonClick(e) {
          e.preventDefault();
          formRef.value?.validate((errors) => {
            if (!errors) {
              if (upimages.value) {
                editorImage.value = upimages.value;
              } else {
                editorImage.value = tableDate.value.photo;
              }
              proxy
                .$axios({
                  url: '/api/certificate/index/edit',
                  method: 'post',
                  data: {
                    id: tableDate.value.id,
                    uid: tableDate.value.uid,
                    name: tableDate.value.name,
                    level: tableDate.value.level,
                    number: tableDate.value.number,
                    gain_time: formattedValue.value,
                    review_time: formattedValues.value,
                    photo: editorImage.value,
                    admin_id: 111,
                    admin_name: '张',
                  },
                })
                .then((res) => {
                  console.log(res.data);
                  if (res.data.code == 1) {
                    message.success('编辑成功');
                    lists();
                    showModals.value = false;
                  }
                });
            } else {
              console.log(errors);
              message.error('保存失败');
            }
          });
        },
        handleValidateButtonClicks(e) {
          e.preventDefault();
          // console.log(newModel.id);
          // console.log(newModel.name);
          // console.log(newModel.selectValue);
          // console.log(newModel.number);
          // console.log(timestampToTime(newModel.time));
          // console.log(timestampToTime(newModel.times));
          // console.log(upimage.value);

          formRefs.value?.validate((errors) => {
            if (!errors) {
              proxy
                .$axios({
                  url: '/api/certificate/index/add',
                  method: 'post',
                  data: {
                    uid: newModel.id,
                    name: newModel.name,
                    level: newModel.selectValue,
                    number: newModel.number,
                    gain_time: timestampToTime(newModel.time),
                    review_time: timestampToTime(newModel.times),
                    photo: upimage.value,
                    admin_id: 1,
                    admin_name: '张三',
                  },
                })
                .then((res) => {
                  console.log(res.data);
                  if (res.data.code == 1) {
                    message.success('添加成功');
                    showNew.value = false;
                    lists();
                  }
                });
            } else {
              console.log(errors);
              message.error('添加失败');
            }
          });
        },
      };
    },
  });
</script>
<style scoped>
  .win_input {
    width: 100%;
    padding: 5px;
  }
  .win_input label {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 5%;
  }
  .win_input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    border: 1px solid rgb(189, 187, 187);
    border-radius: 5px;
    outline-color: #8ebbee;
  }
  .win_input input:focus {
    box-shadow: 1px 1px 3px #4098fc;
    border: none;
  }
  .win_input input:hover {
    border: 1px solid #4098fc;
  }
  .win_input p {
    width: 60px;
    text-align: end;
  }
  .zheng_tops {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .zheng_center {
    display: flex;
  }
  .right_but {
    width: 12%;
    display: flex;
    justify-content: space-between;
  }
  .searchs {
    width: 60%;
    display: flex;
    justify-content: space-around;
  }
</style>
